package com.glela.controller.report;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.glela.ReportExcelUtil;
import com.glela.cache.redis.RedisKeys;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.service.EmailService;
import com.glela.common.util.NumberUtil;
import com.glela.controller.ReportBaseController;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.report.model.CacheDay;
import com.zls.commons.msg.SourceSys;
import com.zls.mail.FileMail;
import com.zls.mail.domain.MailFile;

@Controller
@RequestMapping(value = "/report")
public class ReportController extends ReportBaseController {
	private static final DateTimeFormatter DATE_TIME_YYYY_MM_DDHHMMSSFORMATTER = DateTimeFormat.forPattern(BaseConstants.DATE_FORMAT);

	@Autowired
	private EmailService			emailService;
	@Autowired
	private BaseRestrictionsService	baseRestrictionsService;

	/** 日报 */
	@RequestMapping(value = "/daily", method = RequestMethod.POST)
	public @ResponseBody String daily(@RequestParam Map<String, String> map) {
		try {
			DateTime nowTime = new DateTime();
			nowTime = new DateTime(nowTime.getYear(), nowTime.getMonthOfYear(), nowTime.getDayOfMonth(), 0, 0);//当前日期开始时间
			String begin_time = MapUtils.getString(map, "begin_time", "");
			String end_time = MapUtils.getString(map, "end_time", "");
			int default_days = MapUtils.getIntValue(map, "default_days", 7);

			String url = "";
			String file_name = File.separator + System.currentTimeMillis() + ".xlsx";
			Map<String, String[][]> sheetColumNameMap = new HashMap<>();
			Map<String, String> sheetNameMap = new HashMap<>();
			Map<String, List<Map<String, Object>>> excellSheetData = new LinkedHashMap<String, List<Map<String, Object>>>();

			DateTime startDay = null;
			if (StringUtils.isNotBlank(begin_time)) {
				startDay = DateTime.parse(begin_time, DATE_TIME_YYYY_MM_DDHHMMSSFORMATTER);
			}

			if (startDay == null) {
				startDay = nowTime.minusDays(default_days);
			}
			DateTime endDay = null;
			if (StringUtils.isNotBlank(end_time)) {
				endDay = DateTime.parse(end_time, DATE_TIME_YYYY_MM_DDHHMMSSFORMATTER);
			}
			if (endDay == null || endDay.getMillis() > nowTime.getMillis()) {
				endDay = nowTime;
			}
			long endDayMillis = endDay.getMillis();

			DateTime temp_day = startDay;
			List<Map<String, Object>> sheetRows = null;
			Map<String, String> hgetAll = null;
			String[][] sheetColumnNames = new String[][] { { "  日    期  ", "0", "0", "0" }, { "日新增开店数", "1", "long", "0" }, { "月累计开店数", "2", "long", "0" }, { "小铺来了专属SKIN79日销售额", "3", "double", "¥" }, { "小铺来了其他商品日销售额", "4", "double", "¥" }, { "小铺来了专属SKIN79月累计销售额", "5", "double", "¥" }, { "小铺来了其他商品月累计销售额", "6", "double", "¥" }, { "日订单量", "7", "long", "0" }, { "月累计订单量", "8", "long", "0" }, { "日营业利润", "9", "0", "0" }, { "日交易店铺", "10", "long", "0" }, { "全部累计店铺", "11", "long", "0" }, { "日交易店铺活跃度", "12", "double", "%" } };
			int nextMonth = 0;
			for (int i = 0; temp_day.getMillis() < endDayMillis; i++) {
				nextMonth = temp_day.getMonthOfYear();
				temp_day = startDay.plusDays(i);
				if (i == 0) {
					String monthDay = temp_day.toString(BaseConstants.DATE_FORMAT_YYYYMM);
					sheetColumNameMap.put(monthDay, sheetColumnNames);
					sheetNameMap.put(monthDay, monthDay);
					sheetRows = new ArrayList<Map<String, Object>>();
					excellSheetData.put(monthDay, sheetRows);
					hgetAll = getRedisUtil().hgetAll(RedisKeys.REPORT_DAILY + monthDay);
					if (MapUtils.isEmpty(hgetAll)) {
						//						continue;
					}
				}

				if (temp_day.getMillis() >= endDayMillis) {
					break;
				}
				if (temp_day.getMonthOfYear() != nextMonth) {
					String monthDay = temp_day.toString(BaseConstants.DATE_FORMAT_YYYYMM);
					sheetColumNameMap.put(monthDay, sheetColumnNames);
					sheetNameMap.put(monthDay, monthDay);
					sheetRows = new ArrayList<Map<String, Object>>();
					excellSheetData.put(monthDay, sheetRows);
					hgetAll = getRedisUtil().hgetAll(RedisKeys.REPORT_DAILY + monthDay);
				}

				if (MapUtils.isEmpty(hgetAll)) {
					//					continue;
				}

				String mapKey = temp_day.toString(BaseConstants.DATE_FORMAT_YYYYMMDD);
				CacheDay parseObject = JSONObject.parseObject(hgetAll.get(mapKey), CacheDay.class);
				if (parseObject == null) {
					parseObject = new CacheDay();
				}

				Map<String, Object> resultMap = new HashMap<>();
				sheetRows.add(resultMap);
				int k = 0;
				resultMap.put(sheetColumnNames[k++][1], temp_day.toString(BaseConstants.DATE_FORMAT_YYYY_MM_DD));
				resultMap.put(sheetColumnNames[k++][1], parseObject.getStoreNewNums());
				resultMap.put(sheetColumnNames[k++][1], parseObject.getStoreAccNums());
				resultMap.put(sheetColumnNames[k++][1], NumberUtil.getFloatPrice(parseObject.getSalesAmountDaySkin79()));
				resultMap.put(sheetColumnNames[k++][1], NumberUtil.getFloatPrice(parseObject.getSalesAmountDayNoSelf()));
				resultMap.put(sheetColumnNames[k++][1], NumberUtil.getFloatPrice(parseObject.getSalesAmountMonthSkin79()));
				resultMap.put(sheetColumnNames[k++][1], NumberUtil.getFloatPrice(parseObject.getSalesAmountMonthNoSelf()));
				resultMap.put(sheetColumnNames[k++][1], parseObject.getOrderDaySkin79Nums());
				resultMap.put(sheetColumnNames[k++][1], parseObject.getOrderMonthSkin79Nums());
				resultMap.put(sheetColumnNames[k++][1], "--");
				resultMap.put(sheetColumnNames[k++][1], parseObject.getStoreDayPaySkin79Nums());
				resultMap.put(sheetColumnNames[k++][1], parseObject.getStoreNums());
				if (parseObject.getStoreNums() == 0) {
					resultMap.put(sheetColumnNames[k++][1], 0);
				} else {
					resultMap.put(sheetColumnNames[k++][1], parseObject.getStoreDayPaySkin79Nums() * 1d / parseObject.getStoreNums());
				}
			}

			url = ReportExcelUtil.createExecl(file_name, excellSheetData, sheetColumNameMap, sheetNameMap);
			BaseRestrictions baseRestrictionsForCache = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.EMAIL_REPORT_DAILY);

			FileMail fileMail = new FileMail(SourceSys.XIAOPU);
			if (baseRestrictionsForCache == null) {
				fileMail.getTo().add("liujinlei@pingdagroup.com");
			} else {
				String[] split = StringUtils.split(baseRestrictionsForCache.getName(), "|");
				if (ArrayUtils.isEmpty(split)) {
					fileMail.getTo().add("liujinlei@pingdagroup.com");
				} else {
					for (String string : split) {
						fileMail.getTo().add(string);
					}
				}
			}
			//			fileMail.setSubject("系统日报-" + nowTime.toString(BaseConstants.DATE_FORMAT_YYYY_MM_DD));
			fileMail.setSubject("系统日报");
			fileMail.setText("系统已完成小铺来了日报表数据汇总，请查收附件");
			MailFile mailFile = new MailFile();
			mailFile.setName("小铺来了日报表");
			mailFile.setFilePath(url);
			mailFile.setFileType("xlsx");
			fileMail.getFiles().add(mailFile);
			if (fileMail.checkInfo()) {
				return resultError("邮件发送缺少必填参数：" + url);
			}
			emailService.send(fileMail, "/report/daily.ftl", Pair.of("统计开始时间：", startDay.toString(BaseConstants.DATE_FORMAT)), Pair.of("统计结束时间：", temp_day.minusMillis(1).toString(BaseConstants.DATE_FORMAT)));
			return result(true, "发送成功", url);
		} catch (Exception e) {
			getLogger().error("导出报表异常：{}", e.getMessage(), e);
			return resultError(e.getMessage());
		}
	}
}